# -*- coding: utf8 -*-
import json
import time
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import sys
import datetime
import requests as rs
from ..projectsql.robotsql import getaliyuntoken, weixin_push
from ..decorators import time_statistic
import logging
qa_logger = logging.getLogger('qa_logger')


@time_statistic(3, 'file_link')
def file_translator_from_aliyun(accessKeySecret, accessKeyId, appKey, file_link):
    """
    使用阿里云接口，翻译文件。

    :param accessKeyId: 认证密钥
    :param accessKeySecret: 认证密钥密码
    :param appKey: 项目key
    :param file_link: 文件地址
    :return:
    """
    # 翻译链接实例
    client = AcsClient(accessKeyId, accessKeySecret, "cn-shanghai")

    # 上传待翻译的文件，及配置请求
    req = CommonRequest()
    req.set_domain("filetrans.cn-shanghai.aliyuncs.com")
    req.set_version("2018-08-17")
    req.set_product("nls-filetrans")
    req.set_action_name("SubmitTask")
    req.set_method('POST')
    # 开启智能分轨 task中设置KEY_AUTO_SPLIT : True
    task = {"appkey": appKey, "file_link": file_link, "version": "4.0", "enable_words": True, "auto_split": True}
    task = json.dumps(task)
    req.add_body_params("Task", task)
    try:
        res = client.do_action_with_exception(req)
        res = json.loads(res.decode(encoding='UTF-8'))
        status_text = res.get('StatusText')
        if status_text == "SUCCESS":
            task_id = res["TaskId"]
            qa_logger.info('翻译任务已提交 file_link：%s task_id:%s', file_link, task_id)
        else:
            task_id = ''
            qa_logger.info('翻译任务提交失败 file_link：%s result_data:%s', file_link, res)
        return task_id

    except Exception as e:
        error_type = type(e)
        error_text = str(e)
        qa_logger.error('file:%s appKey:%s error:%s %s', file_link, appKey, error_type, error_text)
        weixin_push('质检翻译出错 file_translator_from_aliyun', error_text, 'ServerException')
        return ''


@time_statistic(0, 'taskId')
def get_audio_asr_result(taskId, akId, akSecret):
    # 创建CommonRequest，设置任务ID。获取返回识别结果
    getRequest = CommonRequest()
    getRequest.set_domain("filetrans.cn-shanghai.aliyuncs.com")
    getRequest.set_version("2018-08-17")
    getRequest.set_product("nls-filetrans")
    getRequest.set_action_name("GetTaskResult")
    getRequest.set_method('GET')
    getRequest.add_query_param("TaskId", taskId)
    # 提交录音文件识别结果查询请求
    # 以轮询的方式进行识别结果的查询，直到服务端返回的状态描述符为"SUCCESS"、"SUCCESS_WITH_NO_VALID_FRAGMENT"，
    # 或者为错误描述，则结束轮询。
    try:
        client = AcsClient(akId, akSecret, "cn-shanghai")
        getResponse = client.do_action_with_exception(getRequest)
        getResponse = json.loads(getResponse.decode(encoding='UTF-8'))
        statusText = getResponse["StatusText"]
        qa_logger.info('task_id:%s statusText:%s getResponse:%s', taskId, statusText, getResponse)
        if statusText == "SUCCESS":
            # 查询成功
            if 'Result' not in getResponse:
                getResponse["Result"] = {'Words': [], 'Sentences': []}
            the_word = getResponse['Result']['Words']
            del getResponse['Result']['Words']
            return {'code': '1', 'result': str(getResponse), 'word': the_word}
        elif statusText == "QUEUEING" or statusText == "RUNNING":
            return {'code': '2', 'result': ''}
        elif statusText == 'SUCCESS_WITH_NO_VALID_FRAGMENT':  # 语音文件没有录音
            return {'code': '3', 'result': ''}
        elif statusText == 'FILE_TRANS_TASK_EXPIRED':  # TaskId不存在，或者已过期
            return {'code': '5', 'result': ''}
        elif statusText == 'FILE_404_NOT_FOUND':  # 文件不存在
            return {'code': '3', 'result': ''}
        elif statusText == 'USER_BIZDURATION_QUOTA_EXCEED':  # 单日时间超限
            return {'code': '6', 'result': ''}
        else:
            weixin_push('质检翻译出错get_audio_asr_result', str(statusText), 'statusText')
            return {'code': '4', 'result': ''}
    except ServerException as e:
        weixin_push('质检翻译出错get_audio_asr_result', str(e), 'ServerException')
        qa_logger.error('task_id:%s akId:%s error:%s %s', taskId, akId, type(e), str(e))
        return {'code': '-1', 'result': ''}
    except ClientException as e:
        weixin_push('质检翻译出错get_audio_asr_result', str(e), 'ClientException')
        qa_logger.error('task_id:%s akId:%s error:%s %s', taskId, akId, type(e), str(e))
        return {'code': '-1', 'result': ''}


# def change_aisle(getResponse):
#     text_list = getResponse['Result']['Sentences']
#     # text_list =  [{'EndTime': 3850, 'SilenceDuration': 0, 'BeginTime': 100, 'Text': '杨晓江111111。', 'ChannelId': 0, 'SpeechRate': 144, 'EmotionValue': 7.9}, {'EndTime': 8110, 'SilenceDuration': 3, 'BeginTime': 6960, 'Text': '11。', 'ChannelId': 1, 'SpeechRate': 104, 'EmotionValue': 6.1}, {'EndTime': 13320, 'SilenceDuration': 1, 'BeginTime': 9570, 'Text': '哎，哎22。', 'ChannelId': 0, 'SpeechRate': 64, 'EmotionValue': 7.8}, {'EndTime': 18065, 'SilenceDuration': 1, 'BeginTime': 14705, 'Text': '3344。', 'ChannelId': 1, 'SpeechRate': 71, 'EmotionValue': 7.1}, {'EndTime': 24495, 'SilenceDuration': 2, 'BeginTime': 20195, 'Text': '330033333444444。', 'ChannelId': 0, 'SpeechRate': 209, 'EmotionValue': 7.8}, {'EndTime': 28950, 'SilenceDuration': 2, 'BeginTime': 27430, 'Text': '好的好的。', 'ChannelId': 1, 'SpeechRate': 157, 'EmotionValue': 7.1}, {'EndTime': 31800, 'SilenceDuration': 1, 'BeginTime': 30150, 'Text': '55。', 'ChannelId': 0, 'SpeechRate': 72, 'EmotionValue': 8.1}]

#     for text_json in text_list:
#         if text_json['ChannelId'] == 0:
#             text_json['ChannelId'] = 3
#     for text_json in text_list:
#         if text_json['ChannelId'] == 1:
#             text_json['ChannelId'] = 0
#     for text_json in text_list:
#         if text_json['ChannelId'] == 3:
#             text_json['ChannelId'] = 1
#     getResponse['Result']['Sentences'] = text_list
#     return getResponse
